package com.fwh.web.utils.redis;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;
import java.lang.reflect.Field;

/**
 * @Author: fwh
 * @date 2019/4/11&& 17:49
 */
@Component
@Slf4j
public class RedisUtil implements InitializingBean {
    /**
     * 模板加载--redis的配置信息数据
     */
    @Resource(name = "dataRedisTemplate")
    private RedisTemplate<String, Object> redisTemplate;

    private JedisPool jedisPool;

    /**
     * 获取Jedis对象
     *
     * @return
     */
    public Jedis getJedis()  {
        if (jedisPool != null) {
            return jedisPool.getResource();
        } else {
            try {
                afterPropertiesSet();
            } catch (Exception e) {
                log.error("初始化reids异常为:{}",e);
            }
            return jedisPool.getResource();
        }
    }


    /**
     * 实现的初始化接口
     *
     * @param
     * @return void
     * @author:fwh [2019/4/11 && 17:50]
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        Field poolField = ReflectionUtils.findField(JedisConnectionFactory.class, "pool");
        ReflectionUtils.makeAccessible(poolField);
        jedisPool = (JedisPool) ReflectionUtils.getField(poolField, redisTemplate.getConnectionFactory());
    }


}
